<template>
  <!-- 新增深化设计成果 -->
  <base-breadcrumb class="flexMemberInfo-container" :title="$route.meta.title">
    <a-spin :spinning="loading">
      <a-card>
        <title-name :title="$route.meta.title" />
        <!-- 表单 -->
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :form="form"
          :form-list="formOption"
          :is-emit="false"
          @selectOrg="selectOrg"
        >
          <template slot="designUnitName">
            <div>
              <a-input
                v-model="form.designUnitName"
                class="chioseInput"
                style="width: calc(100% - 70px)"
                :disabled="editModel === 0 || businessId"
                placeholder="请选择设计单位名称"
              />
              <a-button class="chioseBtn" :disabled="editModel === 0 || businessId" type="primary" @click="onSearch(1)">
                选择
              </a-button>
            </div>
          </template>
          <template slot="designDeepenMaterialName">
            <div>
              <a-input
                v-model="form.designDeepenMaterialName"
                class="chioseInput"
                style="width: calc(100% - 70px)"
                :disabled="editModel === 0 || businessId"
                placeholder="请选择或输入深化设计资料"
              />
              <!-- :disabled="editModel === 0 || Object.keys(form.deepen).length !==0 || businessId || true" -->
              <a-button class="chioseBtn" type="primary" @click="onSearch(2)"> 选择 </a-button>
            </div>
          </template>
        </custom-form>
        <!-- 表单 -->
      </a-card>
      <div class="tool-btns page-btn-right-top">
        <a-button
          v-if="editModel !== 0 || !businessId"
          class="ml20"
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit(1)"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="editModel !== 0 || !businessId"
          class="ml20"
          :loading="submitLoading"
          type="primary"
          @click="handleSubmit(2)"
        >
          提交
        </a-button>
        <a-button class="ml20" @click="handleClose"> 关闭 </a-button>
      </div>
      <modalDesign
        v-if="visible"
        :visible.sync="visible"
        :modal-type="modalType"
        :form="form"
        @handelShow="handelShow"
        @handleClick="handleModalClick"
      />
    </a-spin>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
  <!-- 新增深化设计成果 -->
</template>
<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import { deepList, searchArr, modalColumns } from './model.js'
import { getAuditProject } from '@/api/themeChoose/themeChoose'
import { list } from '@/api/technical/config'
import { detail, update, add } from '@/api/design/deepDesign/outcomeManagement'
import planningManagement from '@/api/design/deepDesign/planningManagement'
import Moment from 'moment'
import modalDesign from './modalDesign.vue'
import cloneDeep from 'lodash.clonedeep'
import { filter } from 'jszip'
export default {
  name: 'OutcomeManagementForm',
  components: {
    modalDesign
  },
  data() {
    return {
      init: false, // 初始化标识
      editModel: this.$route.query.editModel, // 操作状态:0 查看;1 编辑;2 新增
      id: this.$route.query.id || '',
      businessId: this.$route.query.businessId, //审核流程的businessId
      // 页面加载
      loading: false,
      detailStatus: false,
      // 表单
      form: {
        branchComId: '',
        branchCompany: '',
        projectId: '',
        // designType: '',
        name: '',
        time: '',
        designCategoryId: '',
        designCategoryName: '',
        designDeepenBook: void 0,
        designDeepenBookId: '',
        designDeepenBookName: '',
        designDeepenMaterialName: '', //深化设计资料
        designUnitId: '',
        designUnitName: '',
        deepen: {},
        person: '',
        resultsInfo: '',
        resultsName: '',
        deepDrawTypeId: ''
      },
      // 深化项列表
      deepList,
      deepenList: [],
      //深化设计策划书
      designDeepenBookArr: [],
      // 提交加载
      submitLoading: false,
      // 项目设计管理类别
      designType: {},
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      detailFinished: false,
      //modal
      visible: false,
      MaterialVisible: false,
      modalTitle: '标题',
      editLookFlag: false, // 编辑查看数据回显 首次改变form.deepen
      modalType: '', //true：选择设计资源/false：选择深化设计图纸
      typeslabelList: [], // 深化项
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    // 表单配置
    formOption() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst: this.editModel == 2,
          isNeedAuth:true,
          checkStrictly: true,
          disabled: this.editModel === 0 || !!this.businessId,
          isQueryProjecDetail: false
        },
        // {
        //   label: '分公司',
        //   keyName: 'branchComId',
        //   type: SelectSubCompany,
        //   attrs: {
        //     //表单项关联
        //     autoSelected: this.editModel == 2
        //   },
        //   selectChange: (e) => {
        //     this.form.branchCompany = e.orgName
        //   },
        //   rules: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        //   disabled: this.editModel === 0 || this.businessId
        // },
        // {
        //   label: '项目名称',
        //   keyName: 'projectId',
        //   type: SelectProject,
        //   attrs: {
        //     //表单项关联i
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isEdit: this.editModel == 1,
        //     form: this.form
        //   },
        //   rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        //   disabled: this.editModel === 0 || this.businessId
        // },
        {
          label: '项目设计管理类别',
          keyName: 'designCategoryName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '深化设计成果名称',
          keyName: 'resultsName',
          type: 'BaseInput',
          rules: [{ required: true, message: '请输入深化设计成果名称', trigger: 'change' }],
          disabled: this.editModel === 0 || this.businessId
        },
        {
          label: '深化设计策划书',
          keyName: 'designDeepenBook',
          type: typeof this.form.designDeepenBook === 'string' ? 'BaseInput' : 'a-select',
          data: this.designDeepenBookArr,
          rules: [{ required: true, message: '请输入深化设计策划书', trigger: 'change' }],
          attrs: {
            labelInValue: true
          },
          replaceFields: {
            value: 'id', // 默认为value
            label: 'name' // 默认为label
          },
          disabled: this.editModel === 0 || this.businessId || typeof this.form.designDeepenBook === 'object'
        },
        {
          label: '深化项',
          keyName: 'deepen',
          type: 'a-select',
          data: this.deepenList,
          rules: [{ required: true, message: '请选择深化项', trigger: 'change' }],
          disabled: this.editModel === 0 || this.businessId,
          attrs: {
            labelInValue: true
          }
        },
        {
          label: '设计单位名称',
          keyName: 'designUnitName',
          type: 'BaseInput',
          slot: true,
          rules: [{ required: true, message: '请选择设计单位名称', trigger: 'change' }],
          disabled: this.editModel === 0 || this.businessId
        },
        {
          label: '创建人',
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '深化设计资料',
          keyName: 'designDeepenMaterialName',
          type: 'BaseInput',
          slot: true,
          rules: [{ required: true, message: '请输入深化设计资料', trigger: 'change' }]
        },
        {
          label: '深化设计成果信息',
          keyName: 'resultsInfo',
          type: 'BaseTextarea',
          autoSize: { minRows: 10, maxRows: 10 },
          attrs: {
            maxLength: 3000
          },
          ellipsis: true,
          span: 24,
          rules: [{ required: true, message: '请输入深化设计成果信息', trigger: 'change' }],
          disabled: this.editModel === 0 || this.businessId
        }
      ]
    },
    // 校验
    rules() {
      const obj = {}
      this.formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
 async created() {
    //操作状态:0 查看;1 编辑;2 新增
    this.$route.meta.title = ['查看深化设计成果', '编辑深化设计成果', '新增深化设计成果'][this.editModel]
    this.form.createTime = this.editModel == 2 ? Moment().format('YYYY-MM-DD') : ''
    this.form.creatorName = this.editModel == 2 ? this.userInfo.name : ''
    this.getTypeslabelList()
     //获取通过获取流程配置值
     this.processConfig = await this.$getConfigFn('design_deepen_results_audit')
  },
  mounted() {},
  watch: {
    'form.projectId': {
      handler(val, oldval) {
        if (val) {
          this.getDesignType(val) //项目设计管理类别
          this.handlePlanningManagement(val)
        } else {
          //编辑时项目名称不默认选择，则为空，相关联则也应清空
          this.form.deepen = {} //深化项的值
          this.form.designDeepenBook = '' // 深化设计策划书
          this.form.designDeepenBookId = '' // 深化设计策划书ID
          this.form.designDeepenBookName = '' //深化设计策划书name
          this.form.designCategoryName = '' //深化设计策划书值
        }
      }
    },
    'form.deepen': {
      handler(val) {
        val.key && this.filterCode(val.key)
        // 编辑、查看 回显时 会重置这里的数据 flag下
        if (val.key && this.editModel != 2 && !this.editLookFlag) {
          this.editLookFlag = true
          return
        }
        this.form.designDeepenMaterialId = ''
        this.form.designDeepenMaterialName = ''
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
      this.form.branchCompany = val[val.length - 2].orgName
    },
    // 获取深化项 匹配code
    getTypeslabelList() {
      list({ type: 11 }).then((res) => {
        this.typeslabelList = res.data
        // editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
        if (this.editModel != 2) {
          this.getDetail()
        }
      })
    },
    filterCode(code) {
      const filterArr = this.typeslabelList.filter((v) => Number(v.code) === Number(code))
      filterArr && filterArr.length && (this.form.deepDrawTypeId = filterArr[0].id)
    },
    onSearch(e) {
      if (this.editModel === 0 || this.businessId) {
        return
      }
      if (e == 1) {
        this.visible = true
        this.modalType = true
      } else if (e == 2) {
        if (!this.form.deepen.key) {
          this.$message.warning({ content: '请先选择深化项！' })
          return
        }
        this.modalType = false
        this.visible = true
      }
    },
    /**
     * @description: 隐藏UnitModal
     */
    handelShow(e) {
      this.visible = e
      this.modalType = ''
    },
    /**
     * @description: 选中数据名称
     */
    handleModalClick(e, modalType) {
      if (modalType) {
        //选中设计单位名称
        this.form.designUnitId = e.id
        this.form.designUnitName = e.name
      } else {
        //选中深化设计资料名称
        this.form.designDeepenMaterialId = e.id
        this.form.designDeepenMaterialName = e.name
      }
    },

    /**
     * @description: 根据深化设计策划书获取深化项
     *  @params:  e:id
     */
    handleDesignDeepenBook(e, callback) {
      // debugger
      if (this.init) {
        this.form.deepen = {}
      }
      if (this.designDeepenBookArr?.length !== 0) {
        this.deepenList = []
        this.designDeepenBookArr.map((item) => {
          if (item.id === e.key) {
            let deepen = item.deepen.split(',')
            deepen.map((item) => {
              switch (item) {
                case '1':
                  this.deepenList.push({ value: '1', label: '钢结构' })
                  break
                case '2':
                  this.deepenList.push({ value: '2', label: '精装修' })
                  break
                case '3':
                  this.deepenList.push({ value: '3', label: '幕墙' })
                  break
                case '4':
                  this.deepenList.push({ value: '4', label: '园林绿化' })
                  break
                case '5':
                  this.deepenList.push({ value: '5', label: '安装' })
                  break
                case '6':
                  this.deepenList.push({ value: '6', label: '加固' })
                  break
              }
            })
          }
        })
      } else {
        this.deepenList = deepList
      }
      callback && callback()
    },
    /**
     * @description: 获取深化设计策划书列表
     *  @params:  projectId项目名称id
     */
    async handlePlanningManagement(val, callback) {
      const query = {
        needCount: true,
        status: '2',
        projectId: val
      }
      const res = await planningManagement.list(query)
      let data = res.data
      if (res.code == 200) {
        // debugger
        this.designDeepenBookArr = data
        this.handleDesignDeepenBook({ key: data[0]?.id })
        if (this.init) {
          if (data.length !== 0) {
            this.form.designDeepenBook = {
              value: data[0].id,
              label: data[0].name
            }
            this.form.designDeepenBookId = data[0].id
            this.form.designDeepenBookName = data[0].name
          } else {
            this.deepenList = deepList
            this.form.designDeepenBook = ''
            this.form.designDeepenBookId = ''
            this.form.designDeepenBookName = ''
          }
        } else {
          this.init = true
        }
      }
    },
    /**
     * @description: 获取项目设计管理类别
     */
    async getDesignType(val) {
      try {
        const { data } = await getAuditProject({
          projectId: val,
          branchComIds: [this.form.branchComId]
        })
        this.designType = {
          designCategoryId: data[0]?.designTypeId || undefined,
          designCategoryName: data[0]?.designTypeName || undefined
        }
        this.form.designCategoryId = this.designType.designCategoryId
        this.form.designCategoryName = this.designType.designCategoryName
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 获取深化设计成果详情
     */
    async getDetail() {
      this.loading = true
      this.detailStatus = true
      const { data, code, message } = await detail({ id: this.id })
      this.loading = false
      if (code === 200) {
        let formData = this.$clone(this.form)
        Object.keys(this.form).forEach((el) => {
          this.form[el] = data[el] || formData[el]
        })
        this.form.id = data.id //该条数据id
        // 如果返回深化设计策划书id为空判断为输入框
        if (data.designDeepenBookId && data.designDeepenBookName) {
          this.form.designDeepenBook = {
            value: data.designDeepenBookId,
            label: data.designDeepenBookName
          }
          this.form.designDeepenBookId = data.designDeepenBookId
          this.form.designDeepenBookName = data.designDeepenBookName
        } else {
          this.form.designDeepenBookId = ''
          this.form.designDeepenBookName = ''
          this.form.designDeepenBook = data.designDeepenBookName
          this.designDeepenBookArr = [] //不为空，深化设计策划书为输入框
        }

        this.form.deepen = {
          key: data.deepenItem.toString(),
          value: data.deepenItemName
        }
      } else {
        this.$message.warning(message)
      }
      this.loading = false
    },
    /**
     * 校验表单
     */
    handleSubmit(val) {
      const type = ['A1类', 'A2类', 'A3类']
      if (type.indexOf(this.form.designCategoryName) === -1) {
        this.$message.success("项目设计管理类别只能为'A1类', 'A2类', 'A3类'！")
        return false
      }
      if (val == 2) {
        // 提交表单
        // 校验表单
        this.$refs.ruleForm.validate((e) => {
          if (e) {
            this.handleSubmitApi(val)
          }
        })
      } else {
        //保存表单
        this.handleSubmitApi(val)
      }
    },
    /**
     * 提交表单
     */
    handleSubmitApi(val) {
      let that = this
      that.setProcessConfig = null;
      let api = [update, add][that.editModel - 1] // 根据操作切换url地址
      let formData = that.$clone(that.form)
      if (this.designDeepenBookArr?.length === 0) {
        //深化设计策划书选项 或 输入时定义
        formData.designDeepenBookName = that.form.designDeepenBook
      } else {
        formData.designDeepenBookId = that.form.designDeepenBook?.value
        formData.designDeepenBookName = that.form.designDeepenBook?.label
      }
      formData.deepenItem = that.form.deepen.key
      formData.deepenItemName = that.form.deepen.label
      formData.resultsStatus = val == '2' ? 1 : 0 //设计成果状态（0：保存草稿/1：提交审批/2：审批通过/3：审批不通过
      that.loading = true
      api({}, formData)
        .then((res) => {
          that.loading = false
          if (res.code == 200) {
            if (val == '2') {
              that.$message.success('提交成功！')
              //提交时，返回id
              that.businessId = res.data;
              that.setProcessConfig = that.processConfig;
              return
            } else {
              that.$message.success('保存成功！')
              that.$multiTab.close()
            }
          }
        })
        .catch(() => {
          that.loading = false
        })
    },
    /**
     * @description: 关闭
     */
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .ant-form {
  .chioseInput {
    height: 28px;
    border-radius: 4px;
  }
  .chioseBtn {
    height: 28px;
    margin-left: 5px;
  }
}
</style>
